<?php
/**
 * 合同分类控制器
 */

declare (strict_types = 1);

namespace app\controller\contract;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Cate extends BaseController
{
    /**
     * 查看合同分类列表
     */
    public function list()
    {
        try {
            $param = Request::param();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            $where = [];
            $where[] = ['delete_time', '=', 0];
            
            // 关键词搜索
            if (!empty($param['keywords'])) {
                $where[] = ['title', 'like', '%' . trim($param['keywords']) . '%'];
            }
            
            // 查询合同分类列表
            $list = Db::name('contract_cate')
                ->where($where)
                ->page($page, $limit)
                ->order('id', 'asc')
                ->select();
            
            // 查询总数
            $count = Db::name('contract_cate')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看单个合同分类信息
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $cate = Db::name('contract_cate')
                ->where('id', $param['id'])
                ->find();
            
            if (empty($cate)) {
                return json(['code' => 404, 'msg' => '合同分类不存在']);
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $cate
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 设置合同分类（获取启用的分类列表）
     */
    public function set()
    {
        try {
            $list = Db::name('contract_cate')
                ->where('status', 1)
                ->where('delete_time', 0)
                ->order('id', 'asc')
                ->select();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 新建合同分类
     */
    public function add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['title'])) {
            return json(['code' => 400, 'msg' => '分类名称不能为空']);
        }
        
        $data = [
            'title' => $param['title'],
            'status' => $param['status'] ?? 1,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            $cateId = Db::name('contract_cate')->insertGetId($data);
            
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $cateId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑合同分类
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        if (empty($param['title'])) {
            return json(['code' => 400, 'msg' => '分类名称不能为空']);
        }
        
        $data = [
            'id' => $param['id'],
            'title' => $param['title'],
            'status' => $param['status'] ?? 1,
            'update_time' => time()
        ];
        
        try {
            Db::name('contract_cate')->update($data);
            
            return json(['code' => 0, 'msg' => '编辑成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '编辑失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除合同分类（软删除）
     */
    public function del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 检查分类下是否有合同
            $contractCount = Db::name('contract')
                ->where('cate_id', $param['id'])
                ->where('delete_time', 0)
                ->count();
            
            if ($contractCount > 0) {
                return json(['code' => 400, 'msg' => '该分类下有合同，不能删除']);
            }
            
            Db::name('contract_cate')
                ->where('id', $param['id'])
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
}